/**
 * 
 */
package com.fsharemobile.client;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import com.fsharemobile.client.APICallTask.OnAPICallCompleted;

import android.text.TextUtils;

/**
 * @author RAD-Dungtm9
 * 
 */
public class PhotoProxy {

	private static final String getListUri = "http://fshare.rad.fpt.net/api/photos/list";

	public PhotoProxy(FClient fclient) {
		super();
		this.fclient = fclient;
	}

	public void getList(int pageIndex, String path,
			final OnGetListCompleted callback) throws Exception {
		// build url params
		StringBuffer sbUrlParams = new StringBuffer("");
		sbUrlParams.append(String.format("/%s?pageIndex=%d", path, pageIndex));
		// call api
		HttpRequest request = new HttpRequest();
		request.setUrl(new URL(getListUri + sbUrlParams.toString()));
		// // set cookie
		// set cookie
		Map<String, String> headerFields = request.getAddedHeaderFields();
		headerFields.put("Cookie",
				TextUtils.join(";", fclient.getCookies().toArray()));
		new APICallTask(fclient.getHttputil(), new OnAPICallCompleted() {
			@Override
			public void onAPICallCompleted(HttpResponse response) {
				// parse result (json)
				int errCode = 0;
				List<Photo> photoList = null;
				try {
					// check errCode
					errCode = response.getHttpCode();
					if (response.getHttpCode() != 200) {
						callback.onGetListCompleted(errCode, null);
						return;
					}
					errCode = 0;
					photoList = new ArrayList<Photo>();
					JSONArray jsoArr = null;
					jsoArr = new JSONArray(response.getBodyAsString());
					// build photo list and return
					for (int i = 0; i < jsoArr.length(); i++) {
						JSONObject jso = jsoArr.getJSONObject(0);
						Photo fphoto = new Photo();
						fphoto.setId(jso.getString("id"));
						fphoto.setName(jso.getString("name"));
						fphoto.setPath(jso.getString("path"));
						fphoto.setCreated(jso.getString("created"));
						fphoto.setSphotolink(jso.getString("s"));
						fphoto.setLphotolink(jso.getString("l"));
						photoList.add(fphoto);
					}
				} catch (Exception jex) {
					System.out.println(jex.toString());
					errCode = 1;
				}
				callback.onGetListCompleted(errCode, photoList);
			}
		}).execute(request);
	}

	public interface OnGetListCompleted {
		void onGetListCompleted(int errCode, List<Photo> photoList);
	}

	private FClient fclient;

}
